package com.mall.annotation;

import com.mall.db.domain.Search;
import com.mall.db.service.SearchService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

@Aspect
@Component
public class SearchAspect {
    @Resource(name = "searchService")
    private SearchService fs;

    //标明切入点标志
    @Pointcut("@annotation(com.mall.annotation.SearchAnnotation)")
    public void pointcut(){}

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point){
        Object result = null;

        try {
            //执行方法
            result = point.proceed();


        }catch (Throwable e){
            e.printStackTrace();
        }


        saveFootprint(point);

        return result;
    }

    //获取request
    public HttpServletRequest getRequest(){
        return ((ServletRequestAttributes) Objects.
                requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    public void saveFootprint(ProceedingJoinPoint point){
        Search search = new Search();

        Object args[] = point.getArgs();


        if (args[1]!=null){
            search.setMid((Integer) args[1]);
        }
        if (args[0]!=null){
            search.setCid((Integer) args[0]);
        }



        search.setCreateTime(new Date());

        fs.save(search);


    }
}
